package com.hgkj.cloud.base.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;


public final class DateTimeUtil {
	/**
	 * 健康报告最近一天
	 *
	 * @param
	 * @return
	 * @throws ParseException
	 */

	public static String heaDay() throws ParseException {
		String date = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date dt = new Date();
		String scheduleDate = sdf.format(dt) + " 12:00:00";
		Date parse = simpleDateFormat2.parse(scheduleDate);
		if (parse.after(dt)) {
			Calendar rightNow = Calendar.getInstance();
			rightNow.setTime(dt);
			rightNow.add(Calendar.DAY_OF_MONTH, -1);
			dt = rightNow.getTime();
		}
		String reStr = sdf.format(dt);
		return reStr;
	}

	public static String heaDay0(String dateStr) throws ParseException {
		String date = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date dt = dateStr == null ? new Date() : stringToDate(dateStr, "yyyy-MM-dd");
		String scheduleDate = sdf.format(dt) + " 12:00:00";
		Date parse = simpleDateFormat2.parse(scheduleDate);
		if (parse.after(dt)) {
			Calendar rightNow = Calendar.getInstance();
			rightNow.setTime(dt);
			rightNow.add(Calendar.DAY_OF_MONTH, -1);
			dt = rightNow.getTime();
		}
		String reStr = sdf.format(dt);
		return reStr;
	}

	/**
	 * 指定天减一天
	 *
	 * @param date
	 * @return
	 * @throws ParseException
	 */


	public static String subDay(String date) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date dt = sdf.parse(date);
		Calendar rightNow = Calendar.getInstance();
		rightNow.setTime(dt);
		rightNow.add(Calendar.DAY_OF_MONTH, -1);
		Date dt1 = rightNow.getTime();
		String reStr = sdf.format(dt1);
		return reStr;
	}

	/**
	 * 指定天加一天
	 *
	 * @param date
	 * @return
	 * @throws ParseException
	 */

	public static String addDay(String date) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date dt = sdf.parse(date);
		Calendar rightNow = Calendar.getInstance();
		rightNow.setTime(dt);
		rightNow.add(Calendar.DAY_OF_MONTH, 1);
		Date dt1 = rightNow.getTime();
		String reStr = sdf.format(dt1);
		return reStr;
	}
	// a integer to xx:xx:xx
	public static String secToTime(int time) {
		String timeStr = null;
		int hour = 0;
		int minute = 0;
		int second = 0;
		if (time <= 0)
			return "00:00";
		else {
			minute = time / 60;
			if (minute < 60) {
				second = time % 60;
				timeStr = unitFormat(minute) + ":" + unitFormat(second);
			} else {
				hour = minute / 60;
				if (hour > 99)
					return "99:59:59";
				minute = minute % 60;
				second = time - hour * 3600 - minute * 60;
				timeStr = unitFormat(hour) + ":" + unitFormat(minute) + ":" + unitFormat(second);
			}
		}
		return timeStr;
	}

	public static String unitFormat(int i) {
		String retStr = null;
		if (i >= 0 && i < 10)
			retStr = "0" + Integer.toString(i);
		else
			retStr = "" + i;
		return retStr;
	}

	/*出生年月日类似1985-02-06*/
	public static int getAgeByBirthday(String pDate) {
		Calendar cal = Calendar.getInstance();

		int yearNow = cal.get(Calendar.YEAR);
		int monthNow = cal.get(Calendar.MONTH)+1;
		int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);

		int yearBirth = Integer.valueOf(pDate.substring(0, 4));
		int monthBirth = Integer.valueOf(pDate.substring(5, 7));
		int dayOfMonthBirth = Integer.valueOf(pDate.substring(8, 10));

		int age = yearNow - yearBirth;

		if (monthNow <= monthBirth) {
			if (monthNow == monthBirth) {
				//monthNow==monthBirth
				if (dayOfMonthNow < dayOfMonthBirth) {
					age--;
				}
			} else {
				//monthNow>monthBirth
				age--;
			}
		}
		return age;
	}
		
	public static Float getFloatAgeByBirthday(Long birth) {
		String pDate = getWholeStringFromUTC(birth);
		Calendar cal = Calendar.getInstance();

		Integer yearNow = cal.get(Calendar.YEAR);
		Integer monthNow = cal.get(Calendar.MONTH)+1;

		Integer yearBirth = Integer.valueOf(pDate.substring(0, 4));
		Integer monthBirth = Integer.valueOf(pDate.substring(5, 7));

		Integer age = yearNow - yearBirth;
		Float shift = (monthNow.floatValue() - monthBirth.floatValue())/12;		
		return age + shift;
	}

	/*日期转UTC时间，返回秒数(准备弃用)*/
	public static Long getUtcFromString(String str){
		Long seconds = 0L;
		if(str!=null && !str.equals("")){
			String tpTme = str+" 00:00:00";
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date time;
			try {
				time = df.parse(tpTme);
				long sec = time.getTime();
				seconds = (Long)(sec/1000);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return seconds;
	}
	
	/*日期转UTC时间，返回秒数*/
	public static Long getUtcFromStrings(String str){
		Long seconds = 0L;
		if(str!=null && !str.equals("")){
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date time;
			try {
				time = df.parse(str);
				seconds = time.getTime();
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return seconds;
	}
	
	/*结束日期转UTC时间，返回秒数*/
	public static Long getEndUtcFromString(String str){
		Long seconds = 0L;
		if(str!=null && !str.equals("")){
			String tpTme = str+" 23:59:59";
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date time;
			try {
				time = df.parse(tpTme);
				long sec = time.getTime();
				seconds = (Long)(sec/1000);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return seconds;
	}

	/*UTC时间转日期时间*/
	public static String getWholeStringFromUTC(Long seconds){
		String dateStr = "";
		long temp = (long)seconds*1000;
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date time = new Date(temp);
		dateStr = df.format(time);
		return dateStr;
	}
	/*UTC时间转日期时间*/
	public static String getTimeStringFromUTC(Long seconds){
		String dateStr = "";
		long temp = (long)seconds*1000;
		SimpleDateFormat df = new SimpleDateFormat("HH:mm");
		Date time = new Date(temp);
		dateStr = df.format(time);
		return dateStr;
	}

	/*UTC时间转日期*/
	public static String getStringFromUTC(Long seconds){
		String dateStr = "";
		long temp = (long)seconds*1000;
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date time = new Date(temp);
		dateStr = df.format(time);
		return dateStr.substring(0,10);
	}

	/*UTC时间转时间*/
	public static String getTimeStringFromUTC(int seconds){
		String timeStr = "";
		long temp = (long)seconds*1000;;
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date time = new Date(temp);
		timeStr = df.format(time);
		return timeStr.substring(11);
	}

	/*日期换算周几*/
	public static String getWeekOfDate(String dateStr) {
		String[] weekDaysName = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
		String[] weekDaysCode = { "0", "1", "2", "3", "4", "5", "6" };
		Date date= null;
		try {
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");//小写的mm表示的是分钟
			date = sdf.parse(dateStr);
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			int intWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
			return weekDaysName[intWeek];
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return null;
	}
	
	/*秒数转换为字符串*/
	public static String getStringFromSeconds(Integer seconds){
		int hour = seconds/(3600);
		int minute = seconds%(3600)/60;
		int second = seconds%(3600)%60;		
		return String.format("%02d:%02d:%02d", hour,minute, second);
	}
	
	/*获取当前时间字符串*/
	public static String getNowString(){
		SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    
		String datetime = tempDate.format(new Date());  	
		return datetime;
	}
	
	/*判断当前时间是否在区间内*/
	public static boolean isBetween(Date sDate,Date eDate){
		if(sDate == null || eDate == null)
			return false;
		Date now = new Date(); 
		if(now.getTime() > sDate.getTime() && now.getTime() < eDate.getTime())
			return true;
		return false;
	}

	/**
	 * 两个时间之差
	 * @param startDate
	 * @param endDate
	 * @return 秒数
	 */
	public static Integer getBetweenSecond(Date startDate, Date endDate) {
		Integer seconds = 0;
		try {
			if(startDate!=null&&endDate!=null) {
				long ss = 0;
				if(startDate.before(endDate)) {
					ss = endDate.getTime() - startDate.getTime();
				}else {
					ss = startDate.getTime() - endDate.getTime();
				}
				seconds = Integer.valueOf((int) (ss/(1000))) ;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return seconds;
	}

	/**
	 * 获取格式化时间 如7天8小时9分
	 * @param seconds 单位秒
	 * @return 如7天8小时9分
	 */
	public static String getFormatTime(Integer seconds) {
		String reStr = "";
		Integer day = 0,hour = 0,minute = 0;
		day = seconds/86400;
		hour = seconds%86400/3600;
		minute = seconds%86400%3600/60;
		if(day > 0) {
			reStr += day+"天";
		}
		if(hour > 0) {
			reStr += hour+"时";
		}
		if(minute > 0) {
			reStr += minute+"分";
		}
		return reStr;
	}

	//String -> date
	public static Date stringToDate(String str) {
		return stringToDate(str, "yyyyMMdd");
	}

	public static Date stringToDate(String str, String style) {
		if (str == null || str.trim().equals("")) {
			return null;
		}
		SimpleDateFormat sdf = new SimpleDateFormat(style);
		Date date = null;
		try {
			date = sdf.parse(str);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return date;
	}

	public static Date stringToDate(String str, String style, String addStr) {
		if (str == null || str.trim().equals("")) {
			return null;
		}
		if (str.length() != style.length()) {
			str += addStr;
		}
		return stringToDate(str, style);
	}

	//date -> String
	public static String dateToString(Date date) {
		return dateToString(date, "yyyyMMdd");
	}

	public static String dateToString(Date date, String style) {
		if (date == null) {
			return null;
		}
		SimpleDateFormat sdf = new SimpleDateFormat(style);
		String s = sdf.format(date);
		return s;
	}

	/**
	 *
	 * @param startTime 开始日期
	 * @param calendarTimeDef 幅度，天=Calendar.DATE，小时=Calendar.HOUR_OF_DAY，秒=Calendar.SECOND，月=Calendar.MONTH
	 * @param times 数量
	 * @param suffixTime 后缀时间
	 * @return
	 * @throws ParseException
	 */
	public static Date dateAdd(Date startTime, int calendarTimeDef, int times, String suffixTime) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar cal = Calendar.getInstance();
		cal.setTime(startTime);
		cal.add(calendarTimeDef, times);
		if (suffixTime == null || suffixTime.equals("")) {
			return cal.getTime();
		}
		SimpleDateFormat sdfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String endTime = sdf.format(cal.getTime()) + suffixTime;
		Date endDate = sdfs.parse(endTime);
		return endDate;
	}

	// 按年加减
	public static Date dateAddByYears(Date startTime, int years, String suffixTime) throws ParseException {
		return dateAdd(startTime, Calendar.YEAR, years, suffixTime);
	}

	// 按月加减
	public static Date dateAddByMonths(Date startTime, int months, String suffixTime) throws ParseException {
		return dateAdd(startTime, Calendar.MONTH, months, suffixTime);
	}

	// 按天加减
	public static Date dateAddByDays(Date startTime, int days, String suffixTime) throws ParseException {
		return dateAdd(startTime, Calendar.DATE, days, suffixTime);
	}

	// 按小时加减
	public static Date dateAddByHours(Date startTime, int hours, String suffixTime) throws ParseException {
		return dateAdd(startTime, Calendar.HOUR_OF_DAY, hours, suffixTime);
	}

	// 按秒加减
	public static Date dateAddBySeconds(Date startTime, int seconds, String suffixTime) throws ParseException {
		return dateAdd(startTime, Calendar.SECOND, seconds, suffixTime);
	}

	public static String dateAddToString(Date startTime, int calendarTimeDef, int times, String suffixTime) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar cal = Calendar.getInstance();
		cal.setTime(startTime);
		cal.add(calendarTimeDef, times);
		if (suffixTime == null || suffixTime.equals("")) {
			return sdf.format(cal.getTime());
		}
		return sdf.format(cal.getTime()) + " " + suffixTime;
	}

	/**
	 * 获取当天0点时间
	 * @param date
	 * @return
	 */
	public static Date getThisDate(Date date) {
		Calendar calendar = Calendar.getInstance();
		// 设置时间
		calendar.setTime(date);
		// 时
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		// 分
		calendar.set(Calendar.MINUTE, 0);
		// 秒
		calendar.set(Calendar.SECOND, 0);
		// 毫秒
		calendar.set(Calendar.MILLISECOND, 0);
		return calendar.getTime();
	}

	/**
	 * 取日期当前月第一天0分0秒
	 * @param date
	 * @return
	 */
	public static Date getThisMonthFirstDate(Date date) {
		Calendar calendar = Calendar.getInstance();
		// 设置时间
		calendar.setTime(date);
		// 第一天
		calendar.set(Calendar.DAY_OF_MONTH, 1);
		// 时
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		// 分
		calendar.set(Calendar.MINUTE, 0);
		// 秒
		calendar.set(Calendar.SECOND, 0);
		// 毫秒
		calendar.set(Calendar.MILLISECOND, 0);
		return calendar.getTime();
	}


	/**
	 * 获取指定月字符串，如格式: yyyy-MM
	 * @param now 当前月
	 * @param style 格式
	 * @param times 加减月数
	 * @return
	 */
	public static String getMonthString(Date now, String style, int times) throws ParseException {
		Date targetMonth = dateAddByMonths(now, times, null);
		return dateToString(targetMonth, style);
	}


	public static final long oneDayMilliseconds = 1000 * 3600 * 24;

	/**
	 * 通过时间秒毫秒数判断两个时间的天数
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	public static int differentDays(Date startTime, Date endTime)
	{
		int days = (int) ((endTime.getTime() - startTime.getTime()) / oneDayMilliseconds);
		return days;
	}

	// 计算纯天数
	public static int differentPureDays(Date startTime, Date endTime)
	{
		Date startDate = getThisDate(startTime);
		Date endDate = getThisDate(endTime);
		int days = (int) ((endDate.getTime() - startDate.getTime()) / oneDayMilliseconds);
		return days;
	}

	/**
	 * 格式化字符串，示例：2023.2.1-2023.2.15
	 * @param style yyyy:年，MM:开始月份，dd:开始日期，EY：结束年，EM:结束月份：ED:结束日期
	 * @param date 日期
	 * @param days 增加天数
	 * @param endDate 结束日期，和 增加天数 互斥           ..-..
	 * @return
	 */
	public static String getFormatMc(String style, Date date, Integer days, Date endDate) throws ParseException {
		Calendar calender = Calendar.getInstance();
		calender.setTime(date);
		int year = calender.get(Calendar.YEAR);
		int month = calender.get(Calendar.MONTH) + 1;
		int day = calender.get(Calendar.DATE);
		Date newDate = endDate == null ? dateAdd(date, Calendar.DATE, days, null) : endDate;
		calender.setTime(newDate);
		int newYear = calender.get(Calendar.YEAR);
		int newMonth = calender.get(Calendar.MONTH) + 1;
		int newDay = calender.get(Calendar.DATE);
		return style.replace("yyyy", Integer.toString(year))
				.replace("MM", Integer.toString(month))
				.replace("dd", Integer.toString(day))
				.replace("EY", Integer.toString(newYear))
				.replace("EM", Integer.toString(newMonth))
				.replace("ED", Integer.toString(newDay));
	}
}


